<?php

namespace Plugins;

use Phalcon\Events\Event;
use Phalcon\Mvc\User\Plugin;
use Phalcon\Mvc\Dispatcher;
use Lib\Response as Response;

class Validate extends Plugin {

    public function beforeDispatch(Event $event, Dispatcher $dispatcher) {
        $signature = (string)$this->request->get('signature');

        if(!empty($signature)) {
            $this->verifiySignature();
        }
    }

    private function verifiySignature() {
        $request = $this->request;
        $config  = $this->getDI()->get('config');
        $priKey  = $config->resources->apiPrikey;

        $signature = (string)$request->get('signature');
        $params    = array_merge((array)$request->getPost(), (array)$request->getQuery());
        unset($params['signature']);
        unset($params['_url']);
        unset($params['_rand_key']);
        unset($params['_only_care']);
        unset($params['appname']);
        unset($params['version_code']);
        unset($params['platform']);

        $params['priKey'] = $priKey;
        ksort($params);

        $pubKey = trim($request->getServer('HTTP_PUBKEY'));
        $origin = $pubKey;

        if(!empty($signature) && !empty($pubKey)) {
            foreach($params as $key => $val) {
                $origin .= sprintf('%s=%s', $key, urlencode($val));
            }

            if(strcasecmp($signature, md5($origin)) === 0) {
                return true;
            }
        }
        echo json_encode('pubkey->' . $pubKey . ' | str-> ' . $origin . ' | encode_str-> ' . md5($origin));
        die();
        throw new \Exception("invalid signature", 90101);
    }
}

